package com.youway.ddd.demo1.jpa.bookstore.entity;

import java.util.Optional;

import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.Table;

import org.springframework.beans.factory.annotation.Autowired;

import com.youway.ddd.demo1.domain.bookstore.Book;
import com.youway.ddd.demo1.domain.bookstore.Bookshelf;
import com.youway.ddd.demo1.jpa.NumericSequenceId;
import com.youway.ddd.demo1.jpa.SpringEntityListener;
import com.youway.ddd.demo1.jpa.bookstore.repository.BookRepository2;
import com.youway.ddd.demo1.jpa.bookstore.repository.BookshelfSpaceRepository2;

@Entity
@Table(name="bookshelf")
@EntityListeners(SpringEntityListener.class)
public class BookshelfEntity2 implements Bookshelf {

    @EmbeddedId
    private NumericSequenceId id;
    
    private String category;
    
    @Autowired transient BookRepository2 bookRepository2;
    @Autowired transient BookshelfSpaceRepository2 bookshelfSpaceRepository2;
    
    public BookshelfEntity2() {
        this.id = new NumericSequenceId();
    }
    @Override
    public NumericSequenceId getId() {
        return id;
    }
    public void setId(NumericSequenceId id) {
        this.id = id;
    }
    @Override
    public String getCategory() {
        return category;
    }
    public void setCategory(String category) {
        this.category = category;
    }
    
    @Override
    public Optional<Space> findBook(String title) {
        return Optional.ofNullable(bookRepository2.findByTitle(title))
                       .map(book -> bookshelfSpaceRepository2.findByBookshelfAndBook(this, book));
    }
    @Override
    public Space store(Book book, int quantity) {
        BookshelfSpaceEntity2 entity = bookshelfSpaceRepository2.findByBookshelfAndBook(this, (BookEntity2) book);
        if(entity == null) {
            entity = new BookshelfSpaceEntity2();
            entity.setBook((BookEntity2) book);
            entity.setBookshelf(this);
        }
        entity.setQuantity(entity.getQuantity() + quantity);
        return bookshelfSpaceRepository2.save(entity);
    }
    
    
    
}